package com.yn.bsc.shiro;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.yn.bsc.model.UserInfo;
import com.yn.bsc.service.UserInfoService;

import tk.mybatis.mapper.entity.Condition;

/**
 * shiro身份校验核心类
 * 
 * @ClassName MyShiroRealm
 * @author z
 * @date 2017年9月14日 下午4:44:42
 */

public class MyShiroRealm extends AuthorizingRealm {

	@Resource
	private UserInfoService userInfoService;

	/**
	 * 认证信息.(身份验证) : Authentication 是用来验证用户身份
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String name = token.getUsername();
		String password = String.valueOf(token.getPassword());

		UserInfo user = null;
		// 从数据库获取对应用户名密码的用户
		Condition condition = new Condition(UserInfo.class);
		condition.createCriteria().andEqualTo("account", name).andEqualTo("password", password);
		List<UserInfo> userList = userInfoService.findByCondition(condition);
		if (userList.size() != 0) {
			user = userList.get(0);
		}
		if (null == user) {
			throw new AccountException("帐号或密码不正确！");
		} else if (user.getIsusing() == 1) {
			throw new DisabledAccountException("此帐号已经设置为禁止登录！");
		} else {
			// 登录成功 更新登录时间 last login time
			user.setLastlogindate(new Date());
			int login_count = user.getLogincount() == null ? 0 : user.getLogincount();
			user.setLogincount(login_count + 1);
			userInfoService.update(user);
		}

		Logger.getLogger(getClass()).info("身份认证成功，登录用户：" + user.getAccount());
		return new SimpleAuthenticationInfo(user, password, getName());
	}

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		return info;
	}
}
